package com.zd01.aop;

import com.zd01.mapper.OperateLogMapper;
import com.zd01.model.OprateLog;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.zd01.anno.LogOperation)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 计算耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        // 构建日志实体
        OprateLog olog = new OprateLog();
        olog.setOperate_emp_id(1); // 这里需要你根据实际情况获取当前用户ID
        olog.setOperate_time(LocalDateTime.now());
        olog.setClass_name(joinPoint.getTarget().getClass().getName());
        olog.setMethod_name(joinPoint.getSignature().getName());
        olog.setMethod_params(Arrays.toString(joinPoint.getArgs()));
        olog.setReturn_value(result != null ? result.toString() : "void");
        olog.setCost_time(costTime);

        // 保存日志
        log.info("记录操作日志: {}", olog);
        operateLogMapper.insertLog(olog);

        return result;
    }


}
